<?php
namespace Index\Controller;
use Think\Controller;
class LoginController extends Controller{

	public function login()
	{
		if(isset($_SESSION['uid'])){
			echo "8888";
		}else{
			$this->weixinlogin();
		}
	}
	public function weixinlogin()
	{

		$rurl = urlencode("http://17216lg531.iask.in/P201702/wx/index.php/index/login/weixinreturn");

		$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbac82045a637c02e&redirect_uri=".$rurl."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

		header("Location:".$url);

	}

	public function weixinreturn()
	{
		$code = I('get.code');
		$appid = "wxbac82045a637c02e";
		$secret = "7c320fea54e77a01fcc59ff7060b04e2";

		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
		
		$data = wcurl($url);

		$_SESSION = $data;

		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN";

		$data = wcurl($url);

		var_dump($data);

	}

	public function show()
	{
		$appId = "wxbac82045a637c02e";
		$timestamp = time();
		$nonceStr = $this->getnonceStr();

		$Index = new IndexController();
		$token = $Index->get_access_token();

		$jsapi_ticket = $this->get_jsapi_ticket($token);

		$url = "http://17216lg531.iask.in".U('index/login/show');

		$str = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;

		$signature =sha1($str);

		$this->assign('appId',$appId);
		$this->assign('timestamp',$timestamp);
		$this->assign('nonceStr',$nonceStr);
		$this->assign('signature',$signature);
		$this->display();
	}

	public function get_jsapi_ticket($token)
    {
    	if(S('ticket')){
    		return S('ticket');
    	}else{
    		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi";
    		$data = wcurl($url);
    		S('ticket',$data['ticket'],7200);
    		return S('ticket');
    	}
    }

	public function getnonceStr($num=16)
	{
		$str ="";

		$temstr ="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";

		for ($i=0; $i < $num ; $i++) { 
			$str.= $temstr[mt_rand(0,strlen($temstr)-1)];
		}

		return $str;
	}

}